package cz.muni.fi.pa165.musiclibrary.musiclibraryweb;

import java.util.Locale;
import java.util.Map;

import org.apache.wicket.util.convert.converter.AbstractConverter;
import org.joda.time.LocalDate;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;

import com.google.common.collect.ImmutableMap;

/**
 *
 * @author Maros Kucbel
 * @date 2012-11-26T19:37:28+0100
 */
public final class LocalDateConverter extends AbstractConverter<LocalDate> {

    public static final Map<String, String> FORMAT_MAP;
    
    static {
        FORMAT_MAP = ImmutableMap.<String, String>builder()//
                .put("sk" , "dd.MM.yyyy")//
                .put("en", "dd/MM/yyyy")//
                .build();
    }
    
    @Override
    public LocalDate convertToObject(String value, Locale locale) {
        String pattern = getDatePattern(locale);
        DateTimeFormatter format = DateTimeFormat.forPattern(pattern).withLocale(locale);
        try {
            return format.parseLocalDate(value);
        } catch (IllegalArgumentException ex) {
            throw newConversionException("Cannot convert to LocalDate.", value, locale);
        }
    }

    @Override
    public String convertToString(LocalDate value, Locale locale) {
        DateTimeFormatter format = DateTimeFormat.forPattern(FORMAT_MAP.get(locale.getLanguage())).withLocale(locale);
        return format.print(value);
    }

    @Override
    protected Class<LocalDate> getTargetType() {
        return LocalDate.class;
    }
    
    /**
     * Returns date pattern for given language. If none is found, pattern for english
     * language will be returned.
     * @param locale Language.
     * @return Date pattern.
     */
    public static String getDatePattern(Locale locale) {
        String pattern = LocalDateConverter.FORMAT_MAP.get(locale.getLanguage());
        if (pattern == null) {
            pattern = LocalDateConverter.FORMAT_MAP.get("en");
        }
        return pattern;
    }

}